
import pygame
import random
import time
from pygame.locals import *

from custom_events import CustomEvents
from scene_object import SceneObject
from scene import Scene
from conf import *

import logging

logger = logging.getLogger(__name__)
logger.setLevel(LOGGING_LEVEL)
logging.basicConfig(format='%(name)s:%(levelname)s:%(message)s')


class SceneRunner:

    def __init__(self, scene):
        self.scene = scene
        self.running = True
        self.scene.set_runner(self)
        self.scene.load_sounds()


    def play_music(self, path):
        self.scene.play_music(path)


    def draw_elements(self):
        self.scene.draw_elements()


    def update_elements(self):
        self.scene.update_elements()

    def handle_event(self):
        self.scene.handle_event()


    def detect_collision(self):
        '''
        detect scene objects that collide tegather.
        send messages to these objects
        '''

        accidents = pygame.sprite.spritecollide(self.scene.jet,
                                                self.scene.enemies,
                                                dokill = False)
        if accidents:
            for e in accidents:
                self.scene.jet.hit(e)

        bullet_demages = pygame.sprite.spritecollide(self.scene.b2,
                                              self.scene.jet_bullets,
                                              dokill = True)
        if bullet_demages:
            self.scene.b2.hit(bullet_demages)
            logger.debug(len(bullet_demages))
            logger.debug(bullet_demages[0].speed)
        pass

    def run_scene(self):
        self.clock = pygame.time.Clock()

        while self.running:
            self.update_elements()
            self.draw_elements()
            self.handle_event()

            self.detect_collision()
            pygame.display.update()
            self.clock.tick(FPS)

        # leave
        self.scene.music_fade_out()




